<template>
  <div class="h-full w-full flex">
    <div
      class="m-auto w-96 border-b-2 h-36 relative overflow-hidden"
      :class="{
        'border-[#FCE3C3]': hasColor,
      }"
    >
      <div ref="dinosaurRef" class="w-max absolute bottom-0 left-16">
        <img v-if="hasColor" :src="dinosaur" class="h-8 w-8" />
        <Icon v-else class="h-8 w-8" icon="mdi:dinosaur-pixel" />
      </div>
      <template v-for="item in blocks" :key="item.key">
        <div
          class="h-6 w-2 bg-black absolute bottom-0"
          :class="{
            '!bg-[#ED8F27]': hasColor,
          }"
          :style="{
            left: `${item.left}px`,
          }"
        ></div>
      </template>
      <a-switch v-model="hasColor" type="line" :style="{ 'background-color': 'transparent' }" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { forEachRight } from 'lodash-es'
import dinosaur from 'imgs/dinosaur.png'

const hasColor = ref(true)
const dinosaurRef = ref()
const score = ref(0)
let started = false
let dinosaurJump: gsap.core.Timeline
let moveInterval: NodeJS.Timeout
let makeInterval: NodeJS.Timeout

async function jump() {
  if (!started) start()
  if (dinosaurJump.isActive()) return
  dinosaurJump.restart()
}
const blocks = ref<{ left: number; key: number }[]>([])

function start() {
  started = true
  moveInterval = setInterval(async () => {
    blocks.value.map((e) => {
      // 滑块移动
      e.left -= 1
    })
    const over = blocks.value.some((e) => {
      if (e.left >= 64 - 8 && e.left <= 64 + 32) {
        // 移入恐龙范围
        if (Number(dinosaurRef.value.style.bottom.replace('px', '')) < 24) {
          // 恐龙碰上了
          return true
        }
      }
      return false
    })
    if (over) {
      moveInterval && clearInterval(moveInterval)
      makeInterval && clearInterval(makeInterval)
      dinosaurJump && dinosaurJump.pause()
      Modal.success({
        content: '游戏结束',
        onOk() {
          blocks.value = []
          started = false
          dinosaurJump.progress(0)
        },
      })
    }
    if (blocks.value[0]?.left <= -8) {
      blocks.value.unshift()
      score.value += 10
    }
  }, 8.6)

  let key = 0
  makeInterval = setInterval(() => {
    blocks.value.push({ left: 378, key: key++ })
  }, 1500)
}

onMounted(() => {
  const onKeyDown = ({ key }: KeyboardEvent) => {
    if (key === ' ') return jump()
  }
  window.addEventListener('keydown', onKeyDown)
  onUnmounted(() => {
    window.removeEventListener('keydown', onKeyDown)
    moveInterval && clearInterval(moveInterval)
    makeInterval && clearInterval(makeInterval)
  })
  dinosaurJump = gsap.timeline({ paused: true }).to(dinosaurRef.value, {
    duration: 0.4,
    bottom: 70,
    repeat: 1,
    yoyo: true,
  })
})
</script>
